using System;
using System.Collections.Generic;
using System.Text;
using Decav.Gatsb.Data;
using Decav.Gatsb.Mobile;
using System.IO;
using Decav.Gatsb.Configuration;

namespace Decav.Gatsb.Application.CommandInterpreters
{
    /// <summary>
    /// Creates a post out of the interpreter context.
    /// </summary>
    public class CreatePostCommandInterpreter : ICommandInterpreter
    {
        #region ICommandInterpreter Members

        public void Execute(CommandInterpreterContext context)
        {
            if (context.ResponseEnded)
                return;

            MobileMessage message = context.InputMessage;
            MmsMessage mediaMessage = message as MmsMessage;

            // if there is nothing we can do with this message because it is emty, then don't bother with it.
            if (!context.MessageHasContent)
                return;

            string body = (message.Body == null) ? string.Empty : message.Body.Trim();

            LocationCheckin currentLocation = GatsbApplication.Current.GetUserLocation(GatsbApplication.Current.CurrentUser);

            if (!currentLocation.LocationSpecified)
            {
                GatsbApplication.Current.SendUserSms("We couldn't post your message because you haven't checked in anywhere.  Tell us where you are, and then repost!");
                return;
            }

            Post post = Post.CreatePost(message.PostTime, body, currentLocation.Location.Id);

            if (mediaMessage != null)
            {
                foreach(FileAttachment file in mediaMessage.Attachments)
                {
                    PostAttachment attachment = new PostAttachment();
                    file.Save(Path.Combine(GatsbConfigurationSection.Current.UserUploadedImagesFolder, attachment.Id.ToString()));
                    post.Attachments.Add(attachment);
                }
            }

            using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                adapt.CreatePost(post);
        }

        #endregion
    }
}
